#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 字节字符串上的字符串操作
问题: 你想在字节字符串上执行普通的文本操作(比如移除，搜索和替换)。
提示:
"""

bstr = b'Hello World'
print(f"{bstr = }")

def recipe1():
    """字节字符串同样也支持大部分和文本字符串一样的内置操作"""
    print(f"{bstr[0:5] = }")

    print(f"{bstr.startswith(b'Hello') = }")
    print(f"{bstr.split() = }")

    print(f"{bstr.replace(b'Heool', b'Hello Cruel') = }")

def recipe2():
    """操作同样也适用于字节数组"""
    data = bytearray(bstr)
    print(f"{data = }")
    print(f"{data[0:5] = }")

    print(f"{data.startswith(b'Hello') = }")
    print(f"{data.split() = }")

    print(f"{data.replace(b'Heool', b'Hello Cruel') = }")    

def recipe3():
    """使用正则表达式匹配字节字符串，但是正则表达式本身必须也是字节串"""
    data = b'FOO:BAR,SPAM'
    import re

    print(f"{data = }")
    print(f"{re.split(b'[:,]', data) = }")

def recipe4():
    """文本字符串上的操作均可用于字节字符串"""
    a = 'Hello World'
    print(f"{a = }")
    print(f"{a[0] = }")
    print(f"{a[1] = }")

    print(f"{bstr[0] = }")
    print(f"{bstr[1] = }")

def recipe5():
    """字节字符串不会提供一个美观的字符串表示，也不能很好的打印出来，除非它们先被解码为一个文本字符串"""
    print(f"{bstr = }")
    print(f"{bstr.decode('ascii') = }")

def recipe6():
    """如果你想格式化字节字符串，你得先使用标准的文本字符串，然后将其编码为字节字符串"""
    print(f"{'{:10s} {:10d} {:10.2f}'.format('ACME', 100, 490.1).encode('ascii') = }") 

def recipe7():
    """字节字符串可能会改变一些操作的语义"""   
    # Write a UTF-8 filename
    with open('jalape\xf1o.txt', 'w') as f:
        f.write('spicy')

    import os
    print(f"{os.listdir('.') = }")
    print(f"{os.listdir(b'.') = }")

def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()
    print('recipe3'.center(20, '*'))
    recipe3()
    print('recipe4'.center(20, '*'))
    recipe4()
    print('recipe5'.center(20, '*'))
    recipe5()
    print('recipe6'.center(20, '*'))
    recipe6()
    print('recipe7'.center(20, '*'))
    recipe7()  
      
if __name__ == '__main__':
    main()       